package com.yvnze.ydyp.modules.document.service.impl;

import com.yvnze.ydyp.common.enums.ErrorCodeEnum;
import com.yvnze.ydyp.common.exception.SysException;
import com.yvnze.ydyp.modules.document.entity.FileRelation;
import com.yvnze.ydyp.modules.document.mapper.FileRelationMapper;
import com.yvnze.ydyp.modules.document.service.IFileRelationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.processing.Filer;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Haipeng Wang  
 * @since 2021-08-14
 */
@Service
public class FileRelationServiceImpl implements IFileRelationService {

    @Autowired
    FileRelationMapper fileRelationMapper;

    /**
     * 添加根节点
     * @param fileInfoId
     */
    @Override
    public void addRootNode(String fileInfoId) {
        FileRelation fileRelation = new FileRelation();
        /**
         * 插入根节点
         */
        fileRelation.setDistance(0);
        fileRelation.setDescendant(fileInfoId);
        fileRelation.setAncestor(fileInfoId);
        fileRelationMapper.insert(fileRelation);
    }

    /**
     * 添加节点
     * 把id 添加到 ancestor 下面
     * @param father
     * @param son
     */
    @Override
    public void addNode(String father, String son) {
        FileRelation fileRelation = new FileRelation();
        //插入node 的file_info id号
        fileRelation.setAncestor(son);
        //插入目标node 的file_info id号
        fileRelation.setDescendant(father);
        fileRelationMapper.insertNode(fileRelation);
        addRootNode(son);
    }

    /**
     * 返回fileInfoId 对应的所有直属字节点
     * @param fileInfoId
     * @return
     */
    @Override
    public List<FileRelation> selectDirNode(String fileInfoId) {
        List<FileRelation> fileRelations = fileRelationMapper.selectDirNode(fileInfoId);
        if (fileRelations.size() == 0 || fileRelations == null){
            throw new SysException(ErrorCodeEnum.NO_DATA);
        }
        return fileRelations;
    }

    /**
     * 返回fileInfoId 对应的所有直属字节点
     * @param fileInfoId
     * @return
     */
    @Override
    public List<FileRelation> selectAllDirNode(String fileInfoId) {
        List<FileRelation> fileRelations = fileRelationMapper.selectAllDirNode(fileInfoId);
        if (fileRelations.size() == 0 || fileRelations == null){
            throw new SysException(ErrorCodeEnum.NO_DATA);
        }
        return fileRelations;
    }

    /**
     * 根据FileInfoId 级联删除所有的子节点
     * @param fileInfoId
     */
    @Override
    public void deleteFileCascade(String fileInfoId) {
        /**
         * 根据FileInfoId 拿到对应的所有子节点的ID
         * 然后再根据子节点的ID 拿到对应的字节点的ID然后逐个删除
         */
        fileRelationMapper.deleteCascade(fileInfoId);
    }





}
